import cv2
import sys
import numpy as np
from PyQt5.QtWidgets import QApplication
import pygetwindow as gw


class Qt5App:
    # hwnd=None#这里的是类全局变量,内部要使用Qt5App读取
    def __init__(self, hWnd):
        # self.就是局部变量
        self.hwnd = hWnd
        # 使用QT5必须初始化QApplication([])
        # 初始化到启动目录
        self.app = QApplication(sys.argv)
        # 选择主屏幕(窗口可以出界或全屏,最小化)
        self.qt5_screen = QApplication.primaryScreen()
        # 根据窗口句柄获取图像
        self.qt5_img = self.qt5_screen.grabWindow(hWnd).toImage()
        # 获取窗口对象
        self.win=gw.Window(hWnd)
    def read(self, x_y_x2_y2=None, hWnd=None):
        # 截取指定窗口图片,转numpy的BGR
        if hWnd != None:
            self.hwnd = hWnd
        else:
            hWnd = self.hwnd

        # 截图方法3
        # 根据窗口句柄获取图像RGBA
        self.qt5_img = self.qt5_screen.grabWindow(hWnd).toImage()
        # print( 'self.qt5_img::::: ',self.qt5_img.l)
        if x_y_x2_y2 == None:
            qt5_img_map = self.qt5_img.copy()
        else:
            # # 截图地图点
            qt5_img_map = self.qt5_img.copy(
                x_y_x2_y2[0],
                x_y_x2_y2[1],
                x_y_x2_y2[2],
                x_y_x2_y2[3],
            )
        qt5_img_map_ptr = qt5_img_map.bits()
        qt5_img_map_ptr.setsize(qt5_img_map.byteCount())
        qt5_img_map_ptr_arr = np.array(qt5_img_map_ptr).reshape(
            qt5_img_map.height(), 
            qt5_img_map.width(), 
            qt5_img_map.depth() // 8
        )
        # grabWindow()是RGBA,透明通道是255白图,去除A通道(保留RGB)
        img_view_cv2=qt5_img_map_ptr_arr[:,:,:3]
        # 如果版本问题出错,需要转色彩空间
        # img_view_cv2 = cv2.cvtColor(qt5_img_map_ptr_arr, cv2.COLOR_RGBA2RGB)
        return img_view_cv2
    
    def getTitle2win_hWnd(self,strTitle):
        # 获取窗口名的hWnd句柄
        if strTitle==None:
            return 0
        else:
            self.win= gw.getWindowsWithTitle(strTitle)[0]
            return self.win._hWnd

    def win_action(self, hWnd=None):
        # 激活指定窗口
        if self.hwnd!=None:
            # 判断是否指定窗口
            if hWnd != None:
                self.hwnd = hWnd
            else:
                hWnd = self.hwnd
            gw.Window(hWnd).activate()

    def winMoveTo(self,x,y):
        # 移动窗口
        self.win.moveTo(x,y)

    def winResizeTo(self,width,height):
        # 修改窗口大小
        self.win.resizeTo(width,height)

    def getwin(self):
        # 返回win窗口对象,放权操作
        return self.win

#  get方法无法移动修改窗口
def getTitle_hWnd(strTitle):
    # 根据窗口名称获取_hWnd窗口句柄
    return gw.getWindowsWithTitle(strTitle)[0]._hWnd

def getPoint_hWnd(x,y):
    # 根据窗口坐标获取窗口句柄
    return gw.getWindowsAt(x,y)[0]._hWnd

def getAction_hWnd():
    # 根据激活的窗口获得句柄(getActiveWindow()必须赋值后调用)
    win=gw.getActiveWindow()
    return win._hWnd


# getActiveWindow方法对象可以修改窗口
def getAction_win():
    # 根据激活的窗口对象
    win=gw.getActiveWindow()
    return win